import 'package:cave_flutter/config/whl_global_config.dart';
import 'package:cave_flutter/model/user_model.dart';
import 'package:cave_flutter/routes/whl_app_pages.dart';
import 'package:cave_flutter/style/whl_style.dart';
import 'package:cave_flutter/utils/extension/string_extension.dart';
import 'package:cave_flutter/utils/whl_date_utils.dart';
import 'package:cave_flutter/widgets/brick/brick.dart';
import 'package:cave_flutter/widgets/refresh_widget.dart';
import 'package:cave_flutter/widgets/whl_button.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:nim_core/nim_core.dart';

import 'chat_fpzn/chat_fpzn_view.dart';
import 'contact/contact_view.dart';
import 'whl_chat_logic.dart';

class WhlChatPage extends StatelessWidget {
  WhlChatPage({Key? key}) : super(key: key);

  final logic = Get.put(WhlChatLogic());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: kAppColor('#F8F8F8'),
      body: GetBuilder<WhlChatLogic>(builder: (logic) {
        return Stack(
          children: [
            Column(
              children: [
                UIRow(
                  margin:
                      EdgeInsets.only(top: ScreenUtil().statusBarHeight + 8.h),
                  children: [
                    UIImage(
                      margin: EdgeInsets.only(left: 18.w, right: 13.w),
                      assetImage: 'icon_chat_add.png',
                      width: 38.w,
                      decoration: BoxDecoration(boxShadow: [
                        BoxShadow(
                          color: Colors.black.withOpacity(0.07),
                          offset: const Offset(0, 8),
                          blurRadius: 30,
                        )
                      ]),
                      onTap: () {
                        Get.toNamed(Routes.newFriend);
                      },
                    ),
                    Expanded(child: Container()),
                    UIText(
                      color: Colors.white,
                      padding: EdgeInsets.only(
                          left: 13.w, right: 11.w, top: 12.w, bottom: 13.w),
                      radius: 20.w,
                      text: '防骗指南',
                      textColor: kAppTextColor,
                      fontSize: 13.sp,
                      fontWeight: FontWeight.bold,
                      marginDrawable: 5.w,
                      startDrawable: UIImage(
                        assetImage: 'icon_chat_tips.png',
                        width: 18.w,
                      ),
                      onTap: () {
                        Get.to(() => Chat_fpznPage());
                      },
                    ),
                    UIImage(
                      margin: EdgeInsets.only(left: 12.w, right: 18.w),
                      assetImage: 'icon_square_notice.png',
                      width: 38.w,
                      decoration: BoxDecoration(boxShadow: [
                        BoxShadow(
                          color: Colors.black.withOpacity(0.07),
                          offset: const Offset(0, 8),
                          blurRadius: 30,
                        )
                      ]),
                      onTap: () {
                        Get.toNamed(Routes.notice);
                      },
                    ),
                  ],
                ),
                UIRow(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  margin: EdgeInsets.only(
                      top: 21.w, left: 24.w, right: 24.w, bottom: 15.h),
                  children: logic.tabList.map((e) {
                    int index = logic.tabList.indexOf(e);
                    return UIStack(
                      margin: EdgeInsets.only(right: 33.w),
                      clipBehavior: Clip.none,
                      // alignment: Alignment.topRight,
                      children: [
                        UIText(
                          text: e,
                          fontSize:
                              logic.selectedIndex == index ? 16.sp : 14.sp,
                          textColor: logic.selectedIndex == index
                              ? kAppSubTextColor
                              : kAppColor('#9C9C9C'),
                          fontWeight: logic.selectedIndex == index
                              ? FontWeight.bold
                              : FontWeight.normal,
                          onTap: () {
                            logic.onPageChanged(index, isClick: true);
                          },
                        ),
                        // Positioned(
                        //   right: -15.w,
                        //   top: -10.w,
                        //   child: UIText(
                        //     padding: EdgeInsets.symmetric(horizontal: 4.w),
                        //     text: '5',
                        //     radius: 100.w,
                        //     height: 18.w,
                        //     width: 18.w,
                        //     alignment: Alignment.center,
                        //     textColor: Colors.white,
                        //     fontSize: 11.sp,
                        //     color: kAppColor('#FF5E2A'),
                        //   ),
                        // )
                      ],
                    );
                  }).toList(),
                ),
                Container(height: 1.w, color: kAppColor('#DEDEDE')),
                // if (logic.selectedIndex != 3)
                //   UIRow(
                //     margin: EdgeInsets.only(left: 13.w, right: 15.w, top: 21.w),
                //     padding: EdgeInsets.only(
                //         left: 7.w, top: 16.w, bottom: 17.w, right: 15.w),
                //     radius: 16.w,
                //     color: Colors.white,
                //     children: [
                //       Expanded(
                //         child: UIText(
                //           text: '没人搭讪？完成资料瞬间提高回复率',
                //           textColor: kAppTextColor,
                //           fontSize: 12.sp,
                //           // fontWeight: FontWeight.bold,
                //         ),
                //       ),
                //       UIText(
                //         text: '忽略',
                //         textColor: kAppTextColor,
                //         fontSize: 12.sp,
                //       ),
                //       UISolidButton(
                //         margin: EdgeInsets.only(left: 4.w),
                //         text: '去完善',
                //         width: 53.w,
                //         height: 25.w,
                //         fontSize: 12.sp,
                //       )
                //     ],
                //   ),
                // if (logic.selectedIndex != 3)
                //   UIImage(
                //     margin: EdgeInsets.only(top: 14.w),
                //     assetImage: 'img_bg_chat_cave.png',
                //     height: 67.w,
                //     onTap: (){
                //       Get.toNamed(Routes.roomPage, arguments: {'showName': 'showName',"toAccountId":"17057639733480000000022"});
                //     },
                //   ),
                Expanded(
                  child: PageView(
                    controller: logic.pageController,
                    onPageChanged: (index) {
                      logic.onPageChanged(index);
                    },
                    children: logic.tabList.map((e) {
                      int index = logic.tabList.indexOf(e);
                      // if (index == 0) {
                      // if (index == 2) {
                      //   return buildCaveItemView();
                      // } else
                      if (index == 1) {
                        return buildCaveItemView();
                      }
                      if (index == 2) {
                        return ContactPage();
                      }
                      return buildConversationListView();
                      // } else {
                      //   return buildFollowedListView();
                      // }
                    }).toList(),
                  ),
                )
              ],
            )
          ],
        );
      }),
    );
  }

  Widget buildConversationListView() {
    return MyRefresh(
      controller: logic.refreshController1,
      onRefresh: () {
        logic.chatRefresh();
      },
      child: CustomScrollView(
        slivers: [
          SliverList(
              delegate: SliverChildBuilderDelegate((context, index) {
            NIMSession model = logic.conversationList[index];
            UserModel? userInfoModel = logic.userInfoData[model.sessionId];
            String showName = logic
                    .onCheckIsCustomerService(userInfoModel?.accountId ?? '')
                ? '在线客服'
                : userInfoModel?.remark ?? userInfoModel?.nickName ?? '未知用户';
            return IntrinsicHeight(
              child: UIRow(
                padding: EdgeInsets.symmetric(horizontal: 13.w, vertical: 16.h),
                children: [
                  UIImage(
                    httpImage: userInfoModel?.avatar?.toImageUrl(),
                    assetPlaceHolder: 'icon_app_logo.png',
                    width: 44.w,
                    height: 44.w,
                    radius: 22.w,
                    fit: BoxFit.cover,
                  ),
                  Expanded(
                    child: UIColumn(
                      margin: EdgeInsets.only(left: 7.w),
                      padding: EdgeInsets.symmetric(vertical: 1.h),
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Row(
                              children: [
                                Container(
                                  constraints: BoxConstraints(maxWidth: 200.w),
                                  child: Text(
                                    showName,
                                    style: TextStyle(
                                      fontSize: 14.sp,
                                      fontWeight: FontWeight.bold,
                                      color: kAppTextColor,
                                    ),
                                    maxLines: 1,
                                    overflow: TextOverflow.ellipsis,
                                  ),
                                ),
                                // UIImage(
                                //   margin: EdgeInsets.only(left: 5.w),
                                //   assetImage: 'icon_svip.png',
                                //   width: 51.w,
                                // ),
                                UIStack(
                                  margin: EdgeInsets.only(left: 4.w),
                                  alignment: Alignment.center,
                                  children: [
                                    UIImage(
                                      assetImage: 'icon_chat_heartbeat.png',
                                      width: 25.w,
                                    ),
                                    UIText(
                                      text: '33',
                                      textColor: Colors.white,
                                      fontSize: 5.sp,
                                    )
                                  ],
                                )
                              ],
                            ),
                            UIText(
                              text: WhlDateUtils.getTimeStringFromWechat(
                                  model.lastMessageTime ?? 0,
                                  isShowTime: true),
                              textColor: kAppTextColor.withOpacity(0.5),
                              fontSize: 10.sp,
                              alignment: Alignment.centerRight,
                            )
                          ],
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            UIText(
                              margin: EdgeInsets.only(left: 2.w),
                              width: 160.w,
                              text: logic.onGetLastMessageContent(model),
                              textColor: kAppColor('#A9A9A9'),
                              shrinkWrap: false,
                              maxLines: 1,
                              fontSize: 12.sp,
                              overflow: TextOverflow.ellipsis,
                            ),
                            if ((model.unreadCount ?? 0) > 0)
                              UIText(
                                padding: EdgeInsets.symmetric(horizontal: 4.w),
                                text: model.unreadCount.toString(),
                                radius: 100.w,
                                height: 18.w,
                                width: 18.w,
                                alignment: Alignment.center,
                                textColor: Colors.white,
                                fontSize: 11.sp,
                                color: kAppColor('#FF5E2A'),
                              )
                          ],
                        )
                      ],
                    ),
                  )
                ],
                onTap: () {
                  logic.doClickConversation(model);
                },
              ),
            );
          }, childCount: logic.conversationList.length))
        ],
      ),
    );
  }

  Widget buildCaveItemView() {
    return MyRefresh(
      controller: logic.refreshController1,
      onRefresh: () {
        logic.chatRefresh();
      },
      child: CustomScrollView(
        slivers: [
          SliverList(
              delegate: SliverChildBuilderDelegate((context, index) {
            NIMSession model = logic.caveList[index];
            Map caveInfoModel = logic.caveInfoData[model.sessionId];
            String getImageBaseUrl =
                WHLGlobalConfig.getInstance().getImageBaseUrl();

            String showName = caveInfoModel['caveName'];
            return IntrinsicHeight(
              child: UIRow(
                padding: EdgeInsets.symmetric(horizontal: 13.w, vertical: 16.h),
                children: [
                  UIImage(
                    httpImage: getImageBaseUrl + caveInfoModel['caveImg'],
                    assetPlaceHolder: 'icon_app_logo.png',
                    width: 44.w,
                    height: 44.w,
                    radius: 22.w,
                    fit: BoxFit.cover,
                  ),
                  Expanded(
                    child: UIColumn(
                      margin: EdgeInsets.only(left: 7.w),
                      padding: EdgeInsets.symmetric(vertical: 1.h),
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Row(
                              children: [
                                Container(
                                  constraints: BoxConstraints(maxWidth: 200.w),
                                  child: Text(
                                    showName,
                                    style: TextStyle(
                                      fontSize: 14.sp,
                                      fontWeight: FontWeight.bold,
                                      color: kAppTextColor,
                                    ),
                                    maxLines: 1,
                                    overflow: TextOverflow.ellipsis,
                                  ),
                                ),
                                // UIImage(
                                //   margin: EdgeInsets.only(left: 5.w),
                                //   assetImage: 'icon_svip.png',
                                //   width: 51.w,
                                // ),
                                // UIStack(
                                //   margin: EdgeInsets.only(left: 4.w),
                                //   alignment: Alignment.center,
                                //   children: [
                                //     UIImage(
                                //       assetImage: 'icon_chat_heartbeat.png',
                                //       width: 25.w,
                                //     ),
                                //     UIText(
                                //       text: '33',
                                //       textColor: Colors.white,
                                //       fontSize: 5.sp,
                                //     )
                                //   ],
                                // )
                              ],
                            ),
                            UIText(
                              text: WhlDateUtils.getTimeStringFromWechat(
                                  model.lastMessageTime ?? 0,
                                  isShowTime: true),
                              textColor: kAppTextColor.withOpacity(0.5),
                              fontSize: 10.sp,
                              alignment: Alignment.centerRight,
                            )
                          ],
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            UIText(
                              margin: EdgeInsets.only(left: 2.w),
                              width: 160.w,
                              text: logic.onGetLastMessageContent(model),
                              textColor: kAppColor('#A9A9A9'),
                              shrinkWrap: false,
                              maxLines: 1,
                              fontSize: 12.sp,
                              overflow: TextOverflow.ellipsis,
                            ),
                            if ((model.unreadCount ?? 0) > 0)
                              UIText(
                                padding: EdgeInsets.symmetric(horizontal: 4.w),
                                text: model.unreadCount.toString(),
                                radius: 100.w,
                                height: 18.w,
                                width: 18.w,
                                alignment: Alignment.center,
                                textColor: Colors.white,
                                fontSize: 11.sp,
                                color: kAppColor('#FF5E2A'),
                              )
                          ],
                        )
                      ],
                    ),
                  )
                ],
                onTap: () {
                  logic.doClickCave(caveInfoModel);
                },
              ),
            );
          }, childCount: logic.caveList.length))
        ],
      ),
    );
  }
}
